package com.one.rope.mvp.web.common.filter;

import com.alibaba.fastjson.JSONObject;
import com.one.rope.mvp.web.common.auth.AdminUserInfo;
import com.one.rope.mvp.web.common.auth.TokenManager;
import com.one.rope.mvp.basecore.bean.AdminBusinessMessage;
import com.one.rope.mvp.basecore.bean.ResponseObject;
import com.one.rope.mvp.web.common.util.SpringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author Weijian.liu
 * @desc 用户退出登录过滤器
 * @date 2018/12/20
 */
public class AdminUserLogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter {

  private static final Logger logger = LoggerFactory.getLogger(AdminUserLogoutFilter.class);

  @Override
  protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
    String loginToken = AdminUserLoginFilter.getToken(request);
    TokenManager tokenManager = SpringUtil.getBean(TokenManager.class);
    if (StringUtils.isBlank(loginToken)) {
//      AdminUserLoginFilter.writeResponse(WebUtils.toHttp(response), JSONObject.toJSONString(ResponseObject.userFailure(AdminBusinessMessage.NOT_LOGIN_IN)));
      return false;
    } else {
      AdminUserInfo user = tokenManager.getAdminUserLoginInfo(loginToken);
      boolean flag = tokenManager.deleteAdminUserId(String.valueOf(user.getAdminUser().getId()));
      if (flag) {
        tokenManager.deleteAdminUserToken(loginToken);
        AdminUserLoginFilter.writeResponse(WebUtils.toHttp(response),
            JSONObject.toJSONString(ResponseObject.userFailure(AdminBusinessMessage.SYSTEM_OK)));
        logger.warn("{[]}退出成功", user.getAdminUser().getAccount());
      } else {
        AdminUserLoginFilter.writeResponse(WebUtils.toHttp(response), JSONObject
            .toJSONString(ResponseObject.userFailure(AdminBusinessMessage.TOKEN_IS_EXPIRE)));
      }
      return false;
    }
  }

}
